package com.fqgj.xjd.user.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.xjd.user.client.enums.FrozenCodeEnum;
import com.fqgj.xjd.user.dao.UserAuthStatusDao;
import com.fqgj.xjd.user.dao.UserFrozenCodeMapDao;
import com.fqgj.xjd.user.entity.UserAuthStatusEntity;
import com.fqgj.xjd.user.entity.UserFrozenCodeMapEntity;
import com.qianli.user.enums.UserAuthStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * name:解冻用户任务
 * auth:ting.li@yuntu-inc.com
 * date:2017/9/29下午4:49
 * version: v1.0.0
 **/
public class UnFrozenUserJOb implements SimpleJob{
    private static final Logger LOGGER = LoggerFactory.getLogger(UnFrozenUserJOb.class);

    private static final int PAGE_SIZE = 500;
    @Autowired
    private UserFrozenCodeMapDao userFrozenCodeMapDao;
    @Autowired
    private UserAuthStatusDao userAuthStatusDao;
    @Override
    public void execute(ShardingContext shardingContext) {
        unFrozen();
    }

    public void unFrozen(){
        long startTime = System.currentTimeMillis();
        LOGGER.info("un frozen user job start...");

        Date now = new Date();
        List<UserFrozenCodeMapEntity> frozenCodeMaps = null;
        //人脸识别拒绝,借款被拒冷冻,账号冷冻,额度评估冷冻
        while (true){
            frozenCodeMaps = userFrozenCodeMapDao.selectUserFrozenCodeMapByCondition(DateUtil.getDateTime(now),
                    null,PAGE_SIZE);
            if(CollectionUtils.isEmpty(frozenCodeMaps)){
                break;
            }
            for(UserFrozenCodeMapEntity entity:frozenCodeMaps){
                entity.setDeleted(true);
                userFrozenCodeMapDao.updateByPrimaryKey(entity);
                //解冻第一轮风控
                if(FrozenCodeEnum.FIRST_RISK_FROZEN.getCode().equals(entity.getFrozenCode())){
                    UserAuthStatusEntity userAuthStatusEntity = userAuthStatusDao.getUserAuthStatusByUserCode(entity.getUserCode());
                    if(userAuthStatusEntity.getFirstRoundRiskStatus() == UserAuthStatusEnum.FAIL.getCode()){
                        userAuthStatusEntity.setFirstRoundRiskStatus(UserAuthStatusEnum.INIT.getCode());
                        userAuthStatusDao.updateByPrimaryKey(userAuthStatusEntity);
                    }
                }
            }
        }
        LOGGER.info("un frozen user job end...,all cost:" + (System.currentTimeMillis()-startTime));
    }
}
